package com.provue.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.provue.common.annotation.DataScope;
import com.provue.common.core.domain.entity.SysRole;
import com.provue.common.core.domain.entity.SysUser;
import com.provue.common.exception.ServiceException;
import com.provue.common.utils.DateUtils;
import com.provue.common.utils.SecurityUtils;
import com.provue.common.utils.StringUtils;
import com.provue.common.utils.spring.SpringUtils;
import com.provue.system.domain.SysUserRole;
import com.provue.system.mapper.SysUserRoleMapper;
import com.provue.system.service.ISysRoleService;
import com.provue.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.provue.admin.mapper.CommonUserMapper;
import com.provue.admin.domain.CommonUser;
import com.provue.admin.service.ICommonUserService;

import static com.provue.common.utils.SecurityUtils.getUserId;
import static com.provue.common.utils.SecurityUtils.getUsername;

/**
 * 用户管理Service业务层处理
 * 
 * @author pro
 * @date 2024-12-04
 */
@Service
public class CommonUserServiceImpl implements ICommonUserService 
{
    @Autowired
    private CommonUserMapper commonUserMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 查询用户管理
     * 
     * @param id 用户管理主键
     * @return 用户管理
     */
    @Override
    public CommonUser selectCommonUserById(Long id)
    {
        return commonUserMapper.selectCommonUserById(id);
    }

    @Override
    public CommonUser selectCommonUserByUserName(String userName) {
        return commonUserMapper.selectCommonUserByUserName(userName);
    }

    /**
     * 查询用户管理列表
     * 
     * @param commonUser 用户管理
     * @return 用户管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<CommonUser> selectCommonUserList(CommonUser commonUser)
    {
        return commonUserMapper.selectCommonUserList(commonUser);
    }

    /**
     * 新增用户管理
     * 
     * @param commonUser 用户管理
     * @return 结果
     */
    @Override
    public String insertCommonUser(CommonUser commonUser)
    {
        // 新增用户时，注册系统用户
        SysUser user = commonToSys(commonUser, null);
        if (!userService.checkUserNameUnique(user))
        {
            return "新增用户'" + user.getUserName() + "'失败，登录账号已存在";
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return "新增用户'" + user.getUserName() + "'失败，手机号码已存在";
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return "新增用户'" + user.getUserName() + "'失败，邮箱账号已存在";
        }
        user.setCreateBy(getUsername());
        commonUser.setCreateTime(DateUtils.getNowDate());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int result = userService.insertUser(user);
        commonUser.setSysUserId(user.getUserId());
        commonUser.setSysUser(user);
        if(result == 0){
            return "新增用户'" + user.getUserName() + "'失败";
        }else{
            commonUserMapper.insertCommonUser(commonUser);
        }
        return "操作成功";
    }

    /**
     * 修改用户管理
     * 
     * @param commonUser 用户管理
     * @return 结果
     */
    @Override
    public int updateCommonUser(CommonUser commonUser)
    {
        commonUser.setUpdateTime(DateUtils.getNowDate());
        SysUser user = commonToSys(commonUser, userService.selectUserById(commonUser.getSysUserId()));
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return 501;
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return 502;
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return 503;
        }
        user.setUpdateBy(getUsername());
        if(userService.updateUser(user) == 0){
            return 0;
        }
        return commonUserMapper.updateCommonUser(commonUser);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetCommonUserPwd(String userName, String password) {
        return commonUserMapper.resetCommonUserPwd(userName, password);
    }


    /**
     * 批量删除用户管理
     * 
     * @param ids 需要删除的用户管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonUserByIds(Long[] ids)
    {
        Long[] userIds = new Long[ids.length];
        for (int i = 0; i < ids.length; i++){
            userIds[i] = commonUserMapper.selectCommonUserById(ids[i]).getSysUserId();
        }
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return 501;
        }
        userService.deleteUserByIds(userIds);
        return commonUserMapper.deleteCommonUserByIds(ids);
    }

    /**
     * 删除用户管理信息
     * 
     * @param id 用户管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonUserById(Long id)
    {
        return commonUserMapper.deleteCommonUserById(id);
    }

    private SysUser commonToSys(CommonUser commonUser, SysUser sysUser){
        if (sysUser == null){
            sysUser = new SysUser();
        }
        // 用户角色分配
        SysRole role = new SysRole();
        role.setRoleId(Long.parseLong(commonUser.getRole()));
        List<SysRole> roles = roleService.selectRoleList(role);
        if(StringUtils.isEmpty(roles)){
            throw new ServiceException("没有权限访问角色数据！");
        }
        Long[] roleIds = new Long[]{Long.parseLong(commonUser.getRole())};
        sysUser.setRoleIds(roleIds);
        sysUser.setDeptId(commonUser.getDeptId());
        sysUser.setAvatar(commonUser.getAvator());
        sysUser.setNickName(commonUser.getNickName());
        sysUser.setPhonenumber(commonUser.getPhonenumber());
        sysUser.setUserName(commonUser.getUserName());
        sysUser.setEmail(commonUser.getEmail());
        sysUser.setCreateTime(commonUser.getCreateTime());
        sysUser.setUpdateTime(commonUser.getUpdateTime());
        sysUser.setPassword(SecurityUtils.encryptPassword(commonUser.getPassword()));
        sysUser.setSex(commonUser.getSex());
        sysUser.setRemark(commonUser.getRemark());
        return sysUser;
    }

}
